import {
  ref,
  onMounted,
  onUnmounted,
  nextTick,
  onActivated,
  onDeactivated
} from 'vue'
import BScroll from '@better-scroll/core'
import PullUp from '@better-scroll/pull-up'
import ObserveDOM from '@better-scroll/observe-dom'

BScroll.use(ObserveDOM)
BScroll.use(PullUp)

function usePullupLoad(hasMoreRef, pageRef, request) {
  const suggest = ref(null)
  const scroll = ref(null)

  onMounted(() => {
    const scrollValue = (scroll.value = new BScroll(suggest.value, {
      momentum: true,
      scrollX: false,
      scrollY: true,
      click: true,
      pullUpLoad: {
        threshold: 20
      },
      observeDOM: true
    }))

    scrollValue.on('pullingUp', pullingUpHandler)

    async function pullingUpHandler() {
      if (hasMoreRef.value) {
        pageRef.value++
        await request()
        await nextTick()
        scrollValue.refresh()
        scrollValue.finishPullUp()
      }
    }
  })

  onUnmounted(() => {
    scroll.value.destroy()
  })

  onActivated(() => {
    scroll.value.enable()
    scroll.value.refresh()
  })

  onDeactivated(() => {
    scroll.value.disable()
  })

  return { suggest, scroll }
}

export default usePullupLoad
